package com.example.hxpc.guidancemanagement.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.hxpc.guidancemanagement.R;
import com.example.hxpc.guidancemanagement.adapter.GridAdapter;
import com.example.hxpc.guidancemanagement.api.BaseApi;
import com.example.hxpc.guidancemanagement.model.JsonBase;
import com.example.hxpc.guidancemanagement.model.JsonFeedback;
import com.example.hxpc.guidancemanagement.tools.LogoutT;
import com.example.hxpc.guidancemanagement.tools.PermisionUtils;
import com.example.hxpc.guidancemanagement.tools.SharePreferenceTools;
import com.example.hxpc.guidancemanagement.tools.ToastTools;
import com.example.hxpc.guidancemanagement.tools.dataTools.OkHttpTools;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent;

import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by tao on 2017/12/6.
 */

public class SendInformationActivity extends Activity implements View.OnClickListener,GridView.OnItemClickListener,BaseApi{
    private TextView te_sure , te_title , te_cancel;
    private ImageView img_add , img_back;
    private EditText edt_say;
    private GridView gridView;
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private GridAdapter gridAdapter;
    private OkHttpTools okHttpTools = new OkHttpTools();
    private Map<String,File> map = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_send_info);
        initView();
    }

    //初始化操作
    public void initView(){
        PermisionUtils.verifyStoragePermissions(this);
        te_sure = (TextView) findViewById(R.id.sure);
        te_sure.setVisibility(View.VISIBLE);
        te_sure.setOnClickListener(this);
        te_sure.setText("发表");
        te_cancel = (TextView) findViewById(R.id.cancel);
        te_cancel.setVisibility(View.VISIBLE);
        te_cancel.setOnClickListener(this);
        te_title = (TextView) findViewById(R.id.te_title);
        te_title.setText("发布信息");
        img_back = (ImageView) findViewById(R.id.back);
        img_back.setVisibility(View.GONE);
        img_add = (ImageView) findViewById(R.id.add_mark);
        img_add.setVisibility(View.GONE);
        edt_say = (EditText) findViewById(R.id.edt_say);
        gridView = (GridView) findViewById(R.id.gridView_p);
        int cols = getResources().getDisplayMetrics().widthPixels/getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setOnItemClickListener(this);
        imagePaths.add("paizhao");
        gridAdapter = new GridAdapter(imagePaths,this);
        gridView.setAdapter(gridAdapter);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cancel:
                finish();
                break;
            case R.id.sure:
                Date day = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                if (map.isEmpty()||map == null){
//                    LogoutT.logout("9999  55555"+ map.isEmpty());
                    okHttpTools.onlyPublishText(this,edt_say.getText().toString(),df.format(day), SharePreferenceTools.getInstance(this).getString("headPhoto"),SharePreferenceTools.getInstance(this).getString("name"));
                    Intent intent = new Intent();
                    intent.putExtra("photo",imagePaths);
                    intent.putExtra("content",edt_say.getText().toString());
                    intent.putExtra("publishTime",df.format(day));
                    intent.putExtra("useHeadPhoto",SharePreferenceTools.getInstance(this).getString("headPhoto"));
                    setResult(1,intent);
                    finish();
                }else {
//                    LogoutT.logout("9999  44444");
                    Intent intent = new Intent();
                    intent.putExtra("photo",imagePaths);
                    intent.putExtra("content",edt_say.getText().toString());
                    intent.putExtra("publishTime",df.format(day));
                    intent.putExtra("useHeadPhoto",SharePreferenceTools.getInstance(this).getString("headPhoto"));
                    setResult(1,intent);
                    finish();
                    okHttpTools.publishActivityInfo(this,edt_say.getText().toString(),map,df.format(day),SharePreferenceTools.getInstance(this).getString("headPhoto"),SharePreferenceTools.getInstance(this).getString("name"));
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String imgs = (String) parent.getItemAtPosition(position);
        LogoutT.logout(imgs+"00000");
        if (imgs.equals("paizhao")){
            LogoutT.logout("hhhhh");
            PhotoPickerIntent intent = new PhotoPickerIntent(SendInformationActivity.this);
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true);
            intent.setSelectedPaths(imagePaths);//已选中的照片地址
            intent.setMaxTotal(9);//设置最多显示数量
            startActivityForResult(intent , REQUEST_CAMERA_CODE);
        }else{
            LogoutT.logout("aaaaaa");
            PhotoPreviewIntent intent = new PhotoPreviewIntent(SendInformationActivity.this);
            intent.setCurrentItem(position);
            intent.setPhotoPaths(imagePaths);
            startActivityForResult(intent , REQUEST_PREVIEW_CODE);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        LogoutT.logout("bbbbbbb");
        if (resultCode == RESULT_OK){
//            LogoutT.logout("qqqqq");
            switch (requestCode){
                //选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
//                    LogoutT.logout(list+"0011");
//                    Uri sourceUri = Uri.fromFile(new File(list.get(0)));
//                    LogoutT.logout(list.size()+"size");
//                    LogoutT.logout(list.get(0)+"   s s ");
                    for(int i = 0 ; i<list.size();i++){
                        File file = new File(list.get(i));
                        map.put("pic"+i,file);
                    }
                    loadAdapter(list);
                    break;
                //预览
                case REQUEST_PREVIEW_CODE:
                    ArrayList<String> listExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
//                    LogoutT.logout(listExtra+"00123");
                    loadAdapter(listExtra);
                    break;
            }
        }
    }

    private void loadAdapter(ArrayList<String> paths) {
        if (imagePaths != null && imagePaths.size()>0){
            imagePaths.clear();
        }
        if (paths.contains("paizhao")){
            paths.remove("paizhao");
        }
        paths.add("paizhao");
        imagePaths.addAll(paths);
        gridAdapter = new GridAdapter(imagePaths,this);
        gridView.setAdapter(gridAdapter);
    }


    @Override
    public void backMsg(String success, JsonBase jsonBase) {
        if (success.equals("true")){
            LogoutT.logout("publishTime     "+ jsonBase.getData().getTime() + jsonBase.getData().getUse_photo());
//            ToastTools.toastMsg(this,jsonBase.getMsg());
//            Intent intent = new Intent();
//            intent.putExtra("photo",imagePaths);
//            intent.putExtra("content",edt_say.getText().toString());
//            intent.putExtra("publishTime",jsonBase.getData().getTime());
//            intent.putExtra("useHeadPhoto",jsonBase.getData().getUse_photo());
//            setResult(1,intent);
//            finish();
        }else {
            ToastTools.toastMsg(this,jsonBase.getMsg());
        }
    }

    @Override
    public void backMsg(String success, JsonFeedback jsonFeedback) {
//        if (success.equals("true")){
//            Intent intent = new Intent();
//
//        }
    }
}
